/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package imagetestclient;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.awt.Image;
import java.awt.image.MemoryImageSource;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author frke0900
 */
public class Main {

    public Main(){
        try { 
            String base64_img = Base64.encode(imageToBinary());
            String sendDataString = new String();
            sendDataString = "{'img':'"+base64_img+"','latitude':'lat','longitude':'long','caption':'cap'}";
            this.sendData(sendDataString);
        } catch(Exception e) {
            System.out.println(e);
        }
                
    }

    private byte[] imageToBinary() throws FileNotFoundException, IOException {
        File img = new File("h:\\1.jpg");
        FileInputStream fis = new FileInputStream(img);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum);
            }
        } catch (IOException ex) {
            System.out.print(ex);
        }
        byte[] bytes = bos.toByteArray();
        return bytes;
    }

    private void sendData(String data) throws MalformedURLException {
        try {
            
            URL url = new URL("http://localhost:8080/service/resources/image");
            HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
            httpCon.setDoOutput(true);
            httpCon.setRequestMethod("PUT");
            OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
            //out.write("{'img': 'bild', 'lat': 'lat', 'long': 'long', 'cap': 'cap'}");
            out.write(data);
            out.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (IOException ex) {
            System.out.println("Test");
            System.out.print(ex);
        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Main main = new Main();
    }

}
